/**
 * 全站权限配置
 *
 */
import router from "./router/router";
import store from "@/store";
import { validatenull } from "@/util/validate";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
NProgress.configure({ showSpinner: false });

/**
 * 导航守卫，相关内容可以参考:
 * https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
 */
router.beforeEach(async (to, from, next) => {
  console.log("导航开始:", from, "->", to);
  // 简化缓冲设置逻辑
  if (to.meta.keepAlive === true) {
    const isTagExists = store.state.tags.tagList.some((ele) => {
      return ele.value === to.fullPath;
    });
    to.meta.$keepAlive = isTagExists;
  } else {
    to.meta.$keepAlive = false;
  }

  // 开始进度条
  NProgress.start();

  const meta = to.meta || {};
  if (store.getters.access_token) {
    console.log("用户已登录，检查路由:", to);
    if (to.path === "/login") {
      console.log("重定向到首页");
      next({ path: "/" });
    } else {
      try {
        // 确保只在用户角色不存在时才获取用户信息
        if (store.getters.roles.length === 0) {
          console.log("获取用户信息...");
          await store.dispatch("GetUserInfo");
          console.log("用户信息获取成功");
        }

        // 添加标签页
        const value = to.query.src || to.fullPath;
        const label = to.query.name || to.name;
        if (
          meta.isTab !== false &&
          !validatenull(value) &&
          !validatenull(label)
        ) {
          store.commit("ADD_TAG", {
            label: label,
            value: value,
            params: to.params,
            query: to.query,
            group: router.$avueRouter.group || [],
          });
        }
        console.log("导航继续");
        next();
      } catch (error) {
        console.error("获取用户信息失败:", error);
        await store.dispatch("FedLogOut");
        console.log("重定向到登录页");
        next({ path: "/login", replace: true });
      }
    }
  } else {
    console.log("用户未登录，检查是否需要认证:", meta.isAuth);
    if (meta.isAuth === false) {
      console.log("不需要认证，继续导航");
      next();
    } else {
      console.log("需要认证，重定向到登录页");
      next("/login");
    }
  }
});

router.afterEach(() => {
  NProgress.done();
  const title = store.getters.tag.label;
  router.$avueRouter.setTitle(title);
});
